package com.sf.fy.uav.applet.firmclient;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sf.fy.uav.common.enums.FirmClientStatusEnum;
import com.sf.fy.uav.common.request.firmclient.FirmClientReq;
import com.sf.fy.uav.common.request.operate.FileAddRequest;
import com.sf.fy.uav.common.response.firmclient.FirmClientRes;
import com.sf.fy.uav.common.response.operational.BusinessLicenseResponse;
import com.sf.fy.uav.common.utils.*;
import com.sf.fy.uav.controller.FileRest;
import com.sf.fy.uav.user.controller.UserCompanyRest;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.entity.UserCompany;
import com.sf.fy.uav.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/home/firm/")
@RequiredArgsConstructor
@Tag(name = "企业管理", description = "企业管理")
public class FirmClientController {
    private final static Logger logger = LoggerFactory.getLogger(FirmClientController.class);
    private final UserCompanyRest userCompanyRest;
    private final PhoneEncoderUtil phoneEncoderUtil;
    private final UserMapper userMapper;
    private final UploadToOssUtils uploadToOssUtils;
    private final FileRest fileRest;
    private final OcrUtil ocrUtil;

    @Value("${oss.public-path:https://sit-ie-uocs-core-shenzhen-xili1-oss.sit.sf-express.com/v1.2/AUTH_sit-IE-UOCS-CORE/sfosspublic001}")
    private String ossPublicPath;

    @GetMapping("get-firm-client")
    @Operation(tags = "获取企业客户管理列表", description = "获取企业客户管理列表")
    @CrossOrigin
    @Parameter(name = "page", description = "页码")
    @Parameter(name = "size", description = "单页条数")
    @Parameter(name = "companyName", description = "企业名称")
    @Parameter(name = "contactPhoneNumber", description = "手机号码")
    @Parameter(name = "status", description = "入驻状态")
    public RespJsonPageData<FirmClientRes> getFirmClients(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String companyName, @RequestParam(required = false) String phoneNumber, @RequestParam(required = false) Byte status) {
        FirmClientReq firmClientReq = new FirmClientReq();
        firmClientReq.setPage(page);
        firmClientReq.setSize(size);
        firmClientReq.setCompanyName(companyName);
        firmClientReq.setPhoneNumber(phoneEncoderUtil.encryptString(phoneNumber));
        firmClientReq.setStatus(status);
        Page<UserCompany> firmClientPageList = userCompanyRest.getFirmClientPageList(firmClientReq);
        Set<String> userIds = firmClientPageList.getRecords().stream().map(UserCompany::getUserId).collect(Collectors.toSet());
        List<User> users = userMapper.selectBatchIds(userIds);
        Map<String, String> userIdAndPhoneMap = users.stream().collect(Collectors.toMap(User::getId, User::getPhoneNumber, (value1, value2) -> value1));
        List<FirmClientRes> firmClientResIes = BeanUtil.copyProperties(firmClientPageList.getRecords(), FirmClientRes.class);
        firmClientResIes.forEach(firmClientRes -> {
            firmClientRes.setStatusName(FirmClientStatusEnum.getName(firmClientRes.getStatus()));
            firmClientRes.setContactPhoneNumber(phoneEncoderUtil.decryptString(firmClientRes.getContactPhoneNumber()));
            firmClientRes.setPhoneNumber(DesensitizedUtil.desensitized(phoneEncoderUtil.decryptString(userIdAndPhoneMap.get(firmClientRes.getUserId())), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
            if (!ObjectUtils.isEmpty(firmClientRes.getMonthlyCreditLimit()) && !ObjectUtils.isEmpty(firmClientRes.getUsedCreditLimit())) {
                firmClientRes.setCorporateCreditLine(firmClientRes.getMonthlyCreditLimit().subtract(firmClientRes.getUsedCreditLimit()));
            }
        });
        return RespJsonPageData.success(firmClientResIes, firmClientPageList.getTotal());
    }

    @PostMapping("edit-firm-client")
    public Rs<Integer> editFirmClient(@RequestBody FirmClientReq firmClientReq) {
        return userCompanyRest.updateFirmClient(firmClientReq);
    }

    @GetMapping("get-firm-by-keyword")
    public Rs<List<UserCompany>> getFirmByKeyWord(@RequestParam(required = false) String keyWord) {
        return userCompanyRest.queryFirmByKeyWord(keyWord);
    }

    @PostMapping("upload-business-license")
    @CrossOrigin
    @Parameter(name = "subject", description = "取值含义businessLicense上传营业执照图片")
    public Rs<BusinessLicenseResponse> uploadPicture(HttpServletRequest request, HttpServletResponse response, @RequestParam String subject, @RequestParam(required = false) String compressionQuality) throws Exception {
        FileAddRequest fileAddRequest = uploadToOssUtils.uploadPicture(request, response, subject, compressionQuality);
        BusinessLicenseResponse businessLicenseResponse = new BusinessLicenseResponse();
        com.sf.fy.uav.entity.File file2 = fileRest.add(fileAddRequest);
        businessLicenseResponse.setFileId(file2.getId());
        businessLicenseResponse.setFilePath(fileAddRequest.getFilePath());
        logger.info("fileAddRequest:{}", fileAddRequest);
        logger.info("filePath:{}", ossPublicPath + fileAddRequest.getFilePath());
        String ocrString = ocrUtil.ocr(ossPublicPath + fileAddRequest.getFilePath());
        logger.info("ocrString:{}", ocrString);
        businessLicenseResponse.setOcrString(ocrString);
        return Rs.success(businessLicenseResponse);
    }

    @GetMapping("get-decode-phoneNumber")
    public String getDecodePhone(@RequestParam String userId) {
        User user = null;
        if (StringUtils.isNotBlank(userId)) {
            user = userMapper.selectById(userId);
        }
        if (!ObjectUtils.isEmpty(user) && StringUtils.isNotBlank(user.getPhoneNumber())) {
            return phoneEncoderUtil.decryptString(user.getPhoneNumber());
        }
        return null;
    }
}
